package controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ReturnDAO;
import dao.WarehouseDAO;
import model.Return;
import model.Warehouse;

/**
 * Servlet implementation class TuihuoController
 */
public class TuihuoController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TuihuoController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			String rejectId = request.getParameter("rejectId");
			String rejectCode = request.getParameter("rejectCode");
			String quantity = request.getParameter("quantity");
			String reason = new String(request.getParameter("reason").getBytes("ISO-8859-1"),"UTF-8");
			String creator = new String(request.getParameter("creator").getBytes("ISO-8859-1"),"UTF-8");
			Date time = new Date();
			String productId = request.getParameter("productId");
			if (new ReturnDAO().save(
					new Return(rejectId, rejectCode, Integer.parseInt(quantity), reason, creator, time, productId))) {
				// 成功
				if(!reason.equals("质量原因")){
					WarehouseDAO dao = new WarehouseDAO();
					Warehouse wr = dao.getByProductId(productId);
					dao.updateEnableQuantity(wr.getEnableQuantity()+Integer.parseInt(quantity), productId);
					dao.updateTotalQuantity(wr.getTotalQunatity()+Integer.parseInt(quantity), productId);
				}
				System.out.println("退货成功");
				String message = URLEncoder.encode("退货成功", "UTF-8");
				response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./tuihuo.jsp");
				
			} else {
				// 失败
				System.out.println("退货失败");
				String message = URLEncoder.encode("退货失败", "UTF-8");
				response.sendRedirect("./view/error.jsp?errorInfo="+message+"&redirect=./tuihuo.jsp");
			
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("退货失败");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
